<script setup>
import { reactive, ref } from "vue";
import alovaInstance from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";
import { deleteTeacher, saveTeacher, updateTeacher } from "@/api/teacher/teacher";
// 文件上传的接口地址
const uploadUrl = import.meta.env.VITE_BASE_URL + '/files/upload'
const formRef = ref();
const data = reactive({
  user: JSON.parse(localStorage.getItem('credit-system-user') || '{}'),
  pageNum: 1,
  pageSize: 5,
  total: 0,
  formVisible: false,
  editForm: false,
  form: {},
  tableData: [],
  username: '',
  realname: '',
  title: '',
  status: '',
  rules: {
    username: [{ required: true, message: "请输入账号", trigger: 'blur' }],
    title: [{ required: true, message: "请选择", trigger: 'blur' }],
    realname: [{ required: true, message: "请输入姓名", trigger: 'blur' }],
    status: [
      { required: true, message: '请选择状态', trigger: 'blur' }
    ],
  }
})

data.form.updateBy = data.user.adminId
const collegeAdminStatus = ref([
  { label: '正常', value: '0' },
  { label: '禁用', value: '1' },
])

const load = () => {
  alovaInstance.Get('/teacher/selectTeacher', {
    params: {
      page: data.pageNum,
      size: data.pageSize,
      collegeId: data.user.collegeId,
      username: data.username,
      realname: data.realname,
      title: data.title,
      status: data.status
    }
  }).then(res => {
    console.log(res);

    if (res.code === '200') {
      data.tableData = res.data?.list
      data.total = res.data?.total
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
  });
}

// 新增
const handleAdd = () => {
  data.form = {}
  data.form.createBy = data.user.username
  data.form.collegeId = data.user.collegeId
  data.form.role = 'TEACHER'
  data.form.status = '0'
  data.formVisible = true
}
// 编辑
const handleEdit = (row) => {
  data.form = { ...row };
  data.editForm = true
}

const closeDialog = () => {
  data.form = {}
  data.editForm = false
}


//新增方法
const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const formData = data.form;
      saveTeacher(formData).then(() => {
        ElMessage.success('添加成功');
        setTimeout(() => { location.reload(); }, 500);
      }).catch(err => {
        ElMessage.error('添加失败：' + err.message);
      });
    }
  })
}

//修改教师信息
const update = () => {
  const formData = data.form;
  updateTeacher(formData).then(() => {
    ElMessage.success('修改成功');
    data.editForm = false
    setTimeout(() => { location.reload(); }, 500);
  }).catch(err => {
    ElMessage.error('修改失败：' + err.message);
  });
}

// 删除
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该记录吗？此操作不可撤销！', '删除确认', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteTeacher(id, data.user.username).then(() => {
      ElMessage.success('删除成功');
      location.reload();
    }).catch(err => {
      ElMessage.error('删除失败：' + err.message);
    });
  })
    .catch(() => {
      // 用户点击取消，无需执行操作
    });
}

// 重置
const reset = () => {
  data.username = ''
  data.realname = ''
  data.title = ''
  data.status = ''
  load()
}

// 处理文件上传的钩子
/*const handleImgSuccess = (res) => {
  data.form.avatar = res.data  // res.data就是文件上传返回的文件路径，获取到路径后赋值表单的属性
}*/

load()
</script>

<template>
  <div>
    <div class="card"
      style="margin-bottom: 10px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <el-input v-model="data.username" style="width: 250px; margin-right: 10px" placeholder="请输入账号查询"></el-input>
      <el-input v-model="data.realname" style="width: 250px; margin-right: 10px" placeholder="请输入姓名查询"></el-input>
      <el-select v-model="data.title" style="width: 250px; margin-right: 10px" placeholder="请选择职称">
        <el-option label="教授" value="教授" />
        <el-option label="副教授" value="副教授" />
        <el-option label="讲师" value="讲师" />
        <el-option label="助教" value="助教" />
      </el-select>
      <el-select v-model="data.status" style="width: 250px; margin-right: 10px" placeholder="请选择账号状态">
        <el-option label="启用" value="0" />
        <el-option label="禁用" value="1" />
      </el-select>
      <el-button type="primary" @click="load">查询</el-button>
      <el-button type="info" style="margin: 0 10px" @click="reset">重置</el-button>
    </div>

    <div class="card"
      style="margin-bottom: 10px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <div style="margin-bottom: 10px">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="danger" style="margin-left: 10px" @click="delBatch">批量删除</el-button>
        <el-button type="info" style="margin-left: 10px">导 入</el-button>
        <el-button type="success" style="margin-left: 10px">导 出</el-button>
      </div>
      <el-table :data="data.tableData" stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column label="编号" prop="teaId"></el-table-column>
        <el-table-column label="账号" prop="username"></el-table-column>
        <el-table-column label="姓名" prop="realname"></el-table-column>
        <el-table-column label="邮件" prop="email"></el-table-column>
        <el-table-column label="电话" prop="phone"></el-table-column>
        <el-table-column label="职称" prop="title"></el-table-column>
        <el-table-column label="所属学院" prop="collegeName"></el-table-column>
        <el-table-column label="状态" prop="status">
          <template #default="scope">
            <el-tag :type="scope.row.status == 0 ? 'success' : 'danger'">
              {{ scope.row.status == 0 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="角色" prop="role">
          <template #default="scope">
            <span v-if="scope.row.role === 'TEACHER'">教师</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="160">
          <template #default="scope">
            <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" @click="handleDelete(scope.row.teaId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="card" style="background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <el-pagination @current-change="load" @size-change="load" v-model:current-page="data.pageNum"
        v-model:page-size="data.pageSize" :page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper"
        :total="data.total" />
    </div>

    <el-dialog title="新增教师信息" width="40%" v-model="data.formVisible" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="data.form" label-width="100px" style="padding-right: 50px" :rules="data.rules" ref="formRef">
        <el-form-item label="账号" prop="username">
          <el-input v-model="data.form.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="姓名" prop="realname">
          <el-input v-model="data.form.realname" autocomplete="off" />
        </el-form-item>
        <el-form-item label="教师职称" prop="title">
          <el-select v-model="data.form.title" placeholder="请选择职称">
            <el-option label="教授" value="教授" />
            <el-option label="副教授" value="副教授" />
            <el-option label="讲师" value="讲师" />
            <el-option label="助教" value="助教" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="data.form.status">
            <el-radio v-for="item in collegeAdminStatus" :key="item.value" :value="item.value">{{ item.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select style="width: 100%" v-model="data.form.role" disabled>
            <el-option value="TEACHER" label="教师"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save()">添 加</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="修改教师信息" width="50%" v-model="data.editForm" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="data.form" label-width="120px" ref="formRef">
        <el-form-item label="登录账号" prop="username">
          <el-input v-model="data.form.username" disabled />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="data.form.realname" disabled />
        </el-form-item>
        <el-form-item label="电子邮箱">
          <el-input v-model="data.form.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="data.form.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="教师职称">
          <el-select v-model="data.form.title" placeholder="请选择职称">
            <el-option label="教授" value="教授" />
            <el-option label="副教授" value="副教授" />
            <el-option label="讲师" value="讲师" />
            <el-option label="助教" value="助教" />
          </el-select>
        </el-form-item>
        <el-form-item label="账号状态">
          <el-radio-group v-model="data.form.status">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog()">取 消</el-button>
          <el-button type="primary" @click="update()">保 存</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>


<style scoped></style>